package org.example.com.editor.command.workspaceCommand;

import org.example.com.editor.command.Command;
import org.example.com.editor.logger.LogManager;
import org.example.com.editor.ui.ConsoleUI;
import org.example.com.editor.workspace.Workspace;

import java.util.List;

public class SaveCommand implements Command {
    private final LogManager logManager;

    public SaveCommand(LogManager logManager) {
        this.logManager = logManager;
    }

    @Override
    public void execute(Workspace workspace, ConsoleUI ui) throws Exception {
        String[] args = ui.getCommandArgs();
        if(args.length==1){
            ui.printInfo("保存当前活动文件");
            workspace.saveFile();
            logManager.onCommandExecuted(workspace.getActiveFile(), args);
            ui.printInfo("保存成功");
        }else if(args.length == 2 && args[1].equals("all")){
            List<String> openedFiles = workspace.getOpenedFiles();
            for(String filePath : openedFiles){
                try{
                    ui.printInfo("保存文件：" + filePath);
                    workspace.saveFile(filePath);
                    logManager.onCommandExecuted(filePath, args);
                } catch (RuntimeException e) {
                    ui.printError(e.getMessage());
                }
            }
        }else if(args.length == 2 ){
            String filePath = args[1];
            ui.printInfo("另存为文件：" + filePath);
            try{
                workspace.saveFile(filePath);
                logManager.onCommandExecuted(filePath, args);
                ui.printInfo("保存成功:" + filePath);
            }catch (RuntimeException e){
                ui.printError(e.getMessage());
            }
        }else{
            ui.printError("用法：save [all|<文件路径>]");
        }

    }

    @Override
    public String getName() {
        return "save";
    }
}
